const WebSocket = require('ws');
const EventEmitter = require('events');

class WebSocketServer extends EventEmitter {
  constructor(httpServer, maxConnections = 5) {
    super();
    this.httpServer = httpServer;
    this.maxConnections = maxConnections;
    this.wss = null;
    this.clients = new Set();
  }

  async start() {
    return new Promise((resolve, reject) => {
      try {
        // 将WebSocket服务器附加到HTTP服务器上
        this.wss = new WebSocket.Server({ 
          server: this.httpServer.server 
        });

        this.wss.on('listening', () => {
          console.log(`WebSocket服务器已启动`);
          resolve();
        });

        this.wss.on('error', (error) => {
          console.error('WebSocket服务器错误:', error);
          this.emit('error', error);
          reject(error);
        });

        this.wss.on('connection', (ws, req) => {
          this.handleConnection(ws, req);
        });

        // WebSocket服务器附加到HTTP服务器后立即就绪
        resolve();

      } catch (error) {
        reject(error);
      }
    });
  }

  handleConnection(ws, req) {
    const clientIp = req.socket.remoteAddress;
    
    // 检查连接数限制
    if (this.clients.size >= this.maxConnections) {
      console.log(`拒绝连接: 已达到最大连接数 (${this.maxConnections})`);
      ws.close(1008, '服务器已达到最大连接数');
      return;
    }

    console.log(`新客户端连接: ${clientIp}`);
    this.clients.add(ws);

    // 发送连接确认消息
    this.sendToClient(ws, {
      type: 'connected',
      serverId: 'ppt-server',
      currentSlide: 1,
      timestamp: Date.now()
    });

    // 处理消息
    ws.on('message', (data) => {
      try {
        const message = JSON.parse(data.toString());
        this.emit('message', message, ws);
      } catch (error) {
        console.error('解析消息失败:', error);
        this.sendToClient(ws, {
          type: 'error',
          message: '无效的消息格式',
          code: 'INVALID_MESSAGE'
        });
      }
    });

    // 处理断开连接
    ws.on('close', () => {
      console.log(`客户端断开连接: ${clientIp}`);
      this.clients.delete(ws);
      this.emit('disconnect', ws);
    });

    // 处理错误
    ws.on('error', (error) => {
      console.error(`客户端错误 (${clientIp}):`, error);
      this.clients.delete(ws);
    });

    // 心跳检测
    ws.isAlive = true;
    ws.on('pong', () => {
      ws.isAlive = true;
    });

    this.emit('connection', ws);
  }

  // 发送消息给指定客户端
  sendToClient(client, message) {
    if (client.readyState === WebSocket.OPEN) {
      try {
        client.send(JSON.stringify(message));
      } catch (error) {
        console.error('发送消息失败:', error);
      }
    }
  }

  // 广播消息给所有客户端
  broadcast(message) {
    const data = JSON.stringify(message);
    this.clients.forEach(client => {
      if (client.readyState === WebSocket.OPEN) {
        try {
          client.send(data);
        } catch (error) {
          console.error('广播消息失败:', error);
        }
      }
    });
  }

  // 启动心跳检测
  startHeartbeat(interval = 30000) {
    this.heartbeatInterval = setInterval(() => {
      this.clients.forEach(ws => {
        if (ws.isAlive === false) {
          console.log('客户端心跳超时，断开连接');
          return ws.terminate();
        }
        ws.isAlive = false;
        ws.ping();
      });
    }, interval);
  }

  // 停止服务器
  stop() {
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval);
    }

    this.clients.forEach(client => {
      client.close(1000, '服务器关闭');
    });

    if (this.wss) {
      this.wss.close(() => {
        console.log('WebSocket服务器已关闭');
      });
    }
  }

  // 获取连接数
  getConnectionCount() {
    return this.clients.size;
  }
}

module.exports = WebSocketServer;
